package com.ushine.web.utils;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author: yls
 * @Date: 2022/02/23 10:43
 * @Description: 日志建表语句组装工具类
 * @Version 1.0
 */
public class LogDataBaseUtils {

    public static void main(String[] args) {
        String str = "db0.log_$->{2022..2029}0$->{1..9},db0.log_$->{2022..2029}$->{10..12}";
        Set<String> tableNames = getTableNames(str);
        tableNames.forEach(tableName -> System.out.println("CREATE TABLE IF NOT EXISTS " + tableName + " LIKE log; "));
    }

    /**
     * 功能描述:
     * 〈 组装分表的表名 〉
     *
     * @param str 表名
     * @return : java.util.Set<java.lang.String>
     * @author : yls
     * @date : 2022/02/23 11:23
     */
    private static Set<String> getTableNames(String str) {
        String[] split = str.split(",");
        Set<String> tableNames = new HashSet<>();
        for (String arr :
                split) {
            String substring = arr.substring(arr.indexOf(".") + 1);
            String[] split1 = substring.split("\\$->", 3);
            String logic = split1[0];
            String year = split1[1];
            year = year.replaceAll("\\{", "");
            String[] years = year.split("\\}", 2);

            String month = split1[2];
            month = month.replaceAll("\\{", "").replaceAll("\\}", "");

            String[] yearsTemp = years[0].split("\\.\\.", 2);
            Integer startYear = Integer.valueOf(yearsTemp[0]);
            Integer endYear = Integer.valueOf(yearsTemp[1]);
            int flag = endYear - startYear;
            for (int i = 0; i <= flag; i++) {
                int tempYear = startYear + i;
                String tempYearResult = logic + tempYear;
                String[] monthsTemp = month.split("\\.\\.", 2);
                Integer startMonth = Integer.valueOf(monthsTemp[0]);
                Integer endMonth = Integer.valueOf(monthsTemp[1]);
                int monthflag = endMonth - startMonth;
                for (int j = 0; j <= monthflag; j++) {
                    int tempMonth = startMonth + j;
                    String resultTableName = tempYearResult + years[1] + tempMonth;
                    tableNames.add(resultTableName);
                }
            }
        }
        return tableNames;
    }

}
